/****************************************************/
 /* Project Name:预约信息管理                              */   
 /* File Name:TdcReservationController              */
 /* Date:2017年3月20日下午5:59:12            */
 /* Description:预约信息的业务逻辑层控制器        */
 /****************************************************/  

package com.thinkgem.jeesite.modules.tdc.reservation.web;

import java.io.IOException;
import java.text.DateFormat;
import java.util.Date;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import com.thinkgem.jeesite.common.config.Global;
import com.thinkgem.jeesite.common.persistence.Page;
import com.thinkgem.jeesite.common.utils.StringUtils;
import com.thinkgem.jeesite.common.web.BaseController;
import com.thinkgem.jeesite.modules.tdc.department.entity.TdcDepartment;
import com.thinkgem.jeesite.modules.tdc.reservation.entity.TdcReservation;
import com.thinkgem.jeesite.modules.tdc.reservation.service.TdcReservationService;
import com.thinkgem.jeesite.modules.tdc.room.entity.TdcRoom;
import com.thinkgem.jeesite.modules.tdc.times.entity.TdcTimes;
import com.thinkgem.jeesite.modules.tdc.visitor.service.TdcVisitorReservationService;

import net.sf.json.JSONObject;
import net.sf.json.JsonConfig;
import net.sf.json.util.CycleDetectionStrategy;

/**
 * 预约信息Controller
 * @author 孟朋朋
 * @version 2017-03-20
 */
@Controller
@RequestMapping(value = "${adminPath}/reservation/tdcReservation")
public class TdcReservationController extends BaseController {

	@Autowired
	private TdcReservationService tdcReservationService;
	
	@ModelAttribute
	public TdcReservation get(@RequestParam(required=false) String id) {
		TdcReservation entity = null;
		if (StringUtils.isNotBlank(id)){
			entity = tdcReservationService.get(id);
		}
		if (entity == null){
			entity = new TdcReservation();
		}
		return entity;
	}
	/**
	 * 
	 * checkbespeakTimes:(检查当天预约时间和当天预约人数)
	 * 
	 * @param response：向客户端回应返回来的信息
	 * @param bespeakNumber:预约编号
	 * @param redirectAttributes：验证成功后的提示信息
	 */
	@RequiresPermissions("reservation:tdcReservation:view")
	@RequestMapping(value = "checkbespeakTimes")
	public void checkbespeakTimes(HttpServletResponse response ,Date bespeakStart,Date bespeakEnd,RedirectAttributes redirectAttributes){
		response.setContentType("application/text;charset=utf-8");
        /*判断日期是星期几*/
		String theWeek=tdcReservationService.getWeek(bespeakStart);
		/*根据星期获取预约配置实体类*/
		TdcTimes tdcTimes=tdcReservationService.findTdcTimes(theWeek);
		/*上午预约数量*/
		int amQuantity=Integer.parseInt(tdcTimes.getAmQuantity());
		/*下午预约数量*/
		int pmQuantity=Integer.parseInt(tdcTimes.getPmQuantity());
	    /*预约配置开始时间*/
		String  start=tdcTimes.getBespeakStart();
		/*预约配置结束时间*/
		String  end=tdcTimes.getBespeakEnd();
		/*预约配置延长时间*/
		String  delay=tdcTimes.getBespeakDelay();
		/*判断预约日期是否合法*/
		boolean n=tdcReservationService.checkDate(bespeakStart, bespeakEnd,start,end,delay);
		/*判断预约日期的上下午*/
		String amOrPm=tdcReservationService.getAmOrPm(bespeakStart);
		/*日期格式化*/
		DateFormat df1 = DateFormat.getDateInstance();
		/*上午或下午的预约总数*/
		int countA=0;
		/**查询上下午预约数量*/
		 if("上午".equals(amOrPm)){
		    String start1=df1.format(bespeakStart)+" 00:00:00";
		    String end1=df1.format(bespeakEnd)+" 12:00:00";
		    countA=tdcReservationService.findCountAm(start1, end1);
		   
		}
		else{  
			String start1=df1.format(bespeakStart)+" 12:00:00";
			String end1=df1.format(bespeakEnd)+" 23:00:00";
			countA=tdcReservationService.findCountAm(start1, end1);
			
		}
		/**判断各种情况并返回特定的值*/
		 try {	
			 if(n){
				 /*1.不在预约时间段*/
				 response.getWriter().print("null");
				   
		    }else if((("上午".equals(amOrPm)&&countA<=amQuantity)||("下午".equals(amOrPm))&&countA<=pmQuantity)){
		    	/*2.验证成功*/ 
		    	response.getWriter().print("true");
			       
		    }else if((("上午".equals(amOrPm)&&countA>amQuantity)||("下午".equals(amOrPm))&&countA>pmQuantity)){
		    	/*3.预约数量已满*/
		    	response.getWriter().print("No");
			      
		    }else{
		    	/*4.其它情况*/
			     response.getWriter().print("false");
			     
		}
		 } catch (IOException e) {
				
				e.printStackTrace();
			}
		
		 
  }

	
	
	/**
	 * 
	 * findStatus:(确认预约状态"已到""未到")
	 * 
	 * @param response：向客户端回应返回来的信息
	 * @param bespeakNumber:预约编号
	 * @param redirectAttributes：验证成功后的提示信息
	 */
	@RequiresPermissions("reservation:tdcReservation:view")
	@RequestMapping(value = "findStatus")
	public void findStatus(HttpServletResponse response ,String bespeakNumber,RedirectAttributes redirectAttributes){
		 response.setContentType("application/text;charset=utf-8");
		 /*根据编号获取预约实体类的信息*/
		 TdcReservation tr=tdcReservationService.getByBespeakNumber(bespeakNumber);
		 /**判断预约实体类是否为空*/
		if(null == tr || "".equals(tr)){
			try {
				response.getWriter().print("null");
				
			} catch (IOException e) {
				addMessage(redirectAttributes, "用户校验失败！失败信息："+e.getMessage());
				e.printStackTrace();
			}
		}
		else{
			/*获得预约人的预约状态*/
			String bespeakStatus=tr.getBespeakStatus();
			/*状态*/
			String bs="未到";
			/*获得预约人的预约房间类型*/
			String roomType=tr.getBespeakType();
			/*房间状态*/
			String roomStatus="空闲中";
			/*获取预约时间*/
			Date start=tr.getBespeakStart();
			/*获取当前系统时间*/
			Date now=new Date();
			/*格式化日期*/
			DateFormat df1 = DateFormat.getDateInstance();
			/*格式化后的预约开始时间*/
			String starts=df1.format(start);
			/*格式化后的当前系统时间*/
			String nows=df1.format(now);
		   /*判断两个时间的大小*/
			boolean n=starts.equals(nows);
			/*根据预约类型获取合适的房间*/
			List<TdcRoom> roomList=tdcReservationService.findRoomList(roomType,roomStatus);
			/**根据条件判断预约人的预约结果*/
		try {
			if(!n){
				/*1.预约时间不是今天*/
				response.getWriter().print("NoNow");
				
			}else if(bs.equals(bespeakStatus)&&roomList.size()>=1){
				/*2.可以进行预约确认*/
				response.getWriter().print("true");
				
				
			}else if(bs.equals(bespeakStatus)&&roomList.size()<1){
				/*3.房间已满，需要手动重置房间再进行预约确认*/
				response.getWriter().print("noRoom");
				
			}
			else{
				/*4.其它情况*/
				response.getWriter().print("false");
			
				
			}
		 }catch (IOException e) {
			addMessage(redirectAttributes, "用户校验失败！失败信息："+e.getMessage());
		}
	}
  }

	
	/**
	 * 
	 * updateStatus:(更新预约信息)
	 * 
	 * @param tdcReservation:预约信息实体类
	 * @param model:是用于前端页面数据展示的
	 * @param redirectAttributes :更新成功后的提示信息
	 * @return 返回到make方法
	 */
	@RequiresPermissions("reservation:tdcReservation:edit")
	@RequestMapping(value = "updateStatus")
	public String updateStatus(TdcReservation tdcReservation, Model model, RedirectAttributes redirectAttributes) {
	  /*获得预约编号*/
	  String bespeakNumber=tdcReservation.getBespeakNumber();
	  /*获得预约房间号*/
	  String bespeakRoom=tdcReservation.getBespeakRoom();
	  /*设置预约状态*/
	  String bespeakStatus="已到";
	  /*设置房间状态*/
	  String roomStatus="使用中";
	  /*设置返回信息*/
	  String message="成功预约";
	  /*设置返回信息*/
	  String messages="请重新选择！";
		if("-1".equals(bespeakRoom)){
			model.addAttribute("message", messages);
		}
		else{
			/*更新预约人预约信息*/
		   tdcReservationService.updateStatus(bespeakRoom, bespeakStatus, bespeakNumber);
		   /*更新房间状态*/
		   tdcReservationService.updateRoomStatus(roomStatus, bespeakRoom);
		   model.addAttribute("message", message);}
			return "tdc/reservation/distributionRoom";
		}
	
	/**
	 * 
	 * make:(预约信息确认)
	 * 
	 * @param request:向服务器提交的信息
	 * @param response:向客户端回应返回来的信息
	 * @param model:是用于前端页面数据展示的
	 * @return 返回到make方法
	 */
	@RequiresPermissions("reservation:tdcReservation:view")
	@RequestMapping(value = "make")
	public String make(TdcReservation tdcReservation,HttpServletRequest request, HttpServletResponse response, Model model) {
	 /*获取预约编号*/
      String bntmp = request.getParameter("BespeakNumber");
      /*获取预约信息实体类*/
      TdcReservation tr =tdcReservationService.getByBespeakNumber(bntmp);
      /*获取预约类型*/
	  String roomType=tr.getBespeakType();
	  /*设置房间状态*/
	  String roomStatus="空闲中";
	  /*设置提示信息*/
	  String message="房间已满！请及时修改房间状态！";
	  /*获取可用房间*/
	  List<TdcRoom> roomList=tdcReservationService.findRoomList(roomType,roomStatus);
	  tdcReservation.setBespeakNumber(bntmp);
	  if(roomList.size()<1){
		  model.addAttribute("message", message);
	  }
	  model.addAttribute("tdcReservation", tdcReservation);
		model.addAttribute("roomList", roomList);
		return "tdc/reservation/distributionRoom";
	}
	/**
	 * 
	 * search:(根据预约编号查询信息)
	 * 
	 * @param request:向服务器提交的信息
	 * @param response:向客户端回应返回来的信息
	 * @param model:是用于前端页面数据展示的
	 */
	@RequiresPermissions("reservation:tdcReservation:view")
	@RequestMapping(value = { "search" })
	public void search(HttpServletRequest request, HttpServletResponse response, Model model) {
		/*获取编号*/
		String bntmp = request.getParameter("bespeakNumber");
		TdcReservation tvr =tdcReservationService.getByBespeakNumber(bntmp);
		try {
			JsonConfig jsonConfig = new JsonConfig();
			jsonConfig.setCycleDetectionStrategy(CycleDetectionStrategy.LENIENT);
			JSONObject json =JSONObject.fromObject(tvr, jsonConfig);
			String json01 = json.toString();
			response.getWriter().print(json01);
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
	
	/**
	 * 
	 * list:(这里用一句话描述这个方法的作用)
	 * 
	 * @param tdcReservation:预约信息实体类
	 * @param request:向服务器提交的信息
	 * @param response:向客户端回应返回来的信息
	 * @param model:是用于前端页面数据展示的
	 * @return 返回到list方法
	 */
	@RequiresPermissions("reservation:tdcReservation:view")
	@RequestMapping(value = "list")
	public String viewlist(TdcReservation tdcReservation, HttpServletRequest request, HttpServletResponse response, Model model) {
		Page<TdcReservation> page = tdcReservationService.findPage(new Page<TdcReservation>(request, response), tdcReservation);
		/*今日预约总量*/
		int todayCounts=tdcReservationService.todayCount();
		/*今日已到总量*/
		int arrivedCounts=tdcReservationService.arrivedCount();
		model.addAttribute("todayCounts", todayCounts);
		model.addAttribute("arrivedCounts", arrivedCounts);
		model.addAttribute("page", page);
		
		return "tdc/reservation/tdcReservationList";
	}
	/**
	 * 
	 * views:(预约信息查看)
	 * 
	 * @param tdcReservation；预约信息实体类
	 * @param model:是用于前端页面数据展示的
	 * @return 返回到添加界面
	 */
	@RequiresPermissions("reservation:tdcReservation:view")
	@RequestMapping(value = "views")
	public String views(HttpServletRequest request,TdcReservation tdcReservation, Model model) {
		String bespeakNumbers=tdcReservation.getBespeakNumber();
		if(null ==bespeakNumbers || "".equals(bespeakNumbers)){
		 String  bespeakNumber=tdcReservationService.getBNumber();
		 tdcReservation.setBespeakNumber(bespeakNumber);
		 tdcReservation.setBespeakStatus("未到");
		}
		List<TdcDepartment> deptList=tdcReservationService.findAllDeptList();
		model.addAttribute("deptList", deptList);
		model.addAttribute("tdcReservation", tdcReservation);
		return "tdc/reservation/tdcReservationViews";
	}
	
	/**
	 * 
	 * form:(添加预约信息)
	 * 
	 * @param tdcReservation；预约信息实体类
	 * @param model:是用于前端页面数据展示的
	 * @return 返回到添加界面
	 */
	@RequiresPermissions("reservation:tdcReservation:view")
	@RequestMapping(value = "form")
	public String form(HttpServletRequest request,TdcReservation tdcReservation, Model model) {
		String bespeakNumbers=tdcReservation.getBespeakNumber();
		if(null ==bespeakNumbers || "".equals(bespeakNumbers)){
		 String  bespeakNumber=tdcReservationService.getBNumber();
		 tdcReservation.setBespeakNumber(bespeakNumber);
		 tdcReservation.setBespeakStatus("未到");
		}
		List<TdcDepartment> deptList=tdcReservationService.findAllDeptList();
		model.addAttribute("deptList", deptList);
		model.addAttribute("tdcReservation", tdcReservation);
		return "tdc/reservation/tdcReservationForm";
	}
	/**
	 * 
	 * history:(查询历史记录)
	 * 
	 * @param tdcReservation：预约信息实体类
	 * @param request:向服务器提交的信息
	 * @param response:向客户端回应返回来的信息
	 * @param model:是用于前端页面数据展示的
	 * @return 返回到History方法
	 */
	@RequiresPermissions("reservation:tdcReservation:view")
	@RequestMapping(value = "history")
	public String history(TdcReservation tdcReservation, HttpServletRequest request, HttpServletResponse response, Model model) {
		Page<TdcReservation> page = tdcReservationService.findPage(new Page<TdcReservation>(request, response), tdcReservation); 
		model.addAttribute("page", page);
		return "tdc/reservation/tdcReservationHistory";
	}
	/**
	 * 
	 * save:(保存预约信息)
	 * 
	 * @param tdcReservation：预约信息实体类
	 * @param model:是用于前端页面数据展示的
	 * @param redirectAttributes:保存预约信息成功后的提示信息
	 * @return 返回到list方法
	 */
	@RequiresPermissions("reservation:tdcReservation:edit")
	@RequestMapping(value = "save")
	public String save(TdcReservation tdcReservation, Model model, RedirectAttributes redirectAttributes,HttpServletRequest request) {
		if (!beanValidator(model, tdcReservation)){
			return form(request,tdcReservation, model);
		}
		String bnumber=tdcReservation.getBespeakNumber();
        /******保存二维码的路径*********/
		String pathyyyymm = "/userfiles/1/images/images2code/" + TdcVisitorReservationService.yyyymm();
		String path = request.getSession().getServletContext().getRealPath(pathyyyymm);
		System.out.println("pathyyyymm--"+pathyyyymm);
		System.out.println("path--"+path);
        /*********生成该预约对象指定的二维码，返回二维码 图片名*******/
		String path2code =tdcReservationService.get2Code(path, bnumber);
		tdcReservation.setBespeak2code(request.getContextPath() + pathyyyymm + path2code);
		tdcReservationService.save(tdcReservation);
		model.addAttribute("tdcReservation", tdcReservation);
		model.addAttribute("redirectAttributes1", "保存预约信息成功");
		addMessage(redirectAttributes, "保存预约信息成功");
//		return "redirect:"+Global.getAdminPath()+"/reservation/tdcReservation/list/?repage";//list界面
		return "tdc/reservation/tdcReservationForm";										//添加界面
	}
	/**
	 * 
	 * delete:(删除预约信息)
	 * 
	 * @param tdcReservation：预约信息实体类
	 * @param redirectAttributes:删除预约信息成功后的提示信息
	 * @return 返回到list方法
	 */
	@RequiresPermissions("reservation:tdcReservation:edit")
	@RequestMapping(value = "delete")
	public String delete(TdcReservation tdcReservation, RedirectAttributes redirectAttributes) {
		tdcReservationService.delete(tdcReservation);
		addMessage(redirectAttributes, "删除预约信息成功");
		return "redirect:"+Global.getAdminPath()+"/reservation/tdcReservation/history/?repage";
	}
	
	

}